package org.makcro.sms.services.chat.web.client.mvc;

import org.makcro.sms.services.chat.web.client.AppEvents;
import org.makcro.sms.services.chat.web.client.Constants;
import org.makcro.sms.services.chat.web.client.mvc.view.LoginView;
import org.makcro.sms.services.chat.web.client.services.login.LoginServiceAsync;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.widget.Info;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class LoginController extends Controller{

	private LoginView loginView;
	
	public LoginController(){
		registerEventTypes(AppEvents.ShowLoginDialog);
		registerEventTypes(AppEvents.ProcessLogin);
	}
	
	@Override
	protected void initialize() {
		// TODO Auto-generated method stub
		super.initialize();
		loginView = new LoginView(this);
	}
	
	@Override
	public void handleEvent(AppEvent event) {
		EventType type = event.getType();
		
		if(type == AppEvents.ShowLoginDialog){
			onShowLogin(event);
		}
		else if(type == AppEvents.ProcessLogin){
			onProcessLogin(event);
		}
		
	}

	private void onProcessLogin(AppEvent event) {
		LoginServiceAsync loginService = Registry.get(Constants.Services.LoginService);
		String[] data = event.getData();
		
		loginService.login(data[0], data[1], new AsyncCallback<Boolean>() {
			
			@Override
			public void onSuccess(Boolean result) {
				// check if result is not null
				if(result == Boolean.TRUE){
					
					onSuccessfulLogin();
				}
				else {
					onLoginFailed();
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
	}

	protected void onSuccessfulLogin() {
		Info.display("Obavestenje", "Uspesna prijava");
		forwardToView(loginView, AppEvents.LoginSuccessful, null);
		Dispatcher.get().dispatch(AppEvents.LoginSuccessful);
	}

	protected void onLoginFailed() {
		Info.display("Obavestenje", "Neuspesna prijava. Korisnicko ime i lozinka se ne poklapaju.");
		forwardToView(loginView, AppEvents.LoginFailed, null);
		
	}

	private void onShowLogin(AppEvent event) {
		forwardToView(loginView, event);
		
	}

}
